package com.aop.demo.jdk.proxy;

import com.aop.demo.aspect.MyAspect;
import com.aop.demo.service.SubjectService;
import com.aop.demo.service.impl.SubjectServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyFactory {
    public final Logger LOGGER = LoggerFactory.getLogger(MyFactory.class);

    public static SubjectService createSubjectService() {
        //1 创建目标类
        final SubjectServiceImpl subjectService = new SubjectServiceImpl();
        //2 创建切面类
        final MyAspect myAspect = new MyAspect();
        SubjectService subjectServiceProxy = (SubjectService) Proxy.newProxyInstance(MyFactory.class.getClassLoader(), subjectService.getClass().getInterfaces(), new InvocationHandler() {
            // 代理类每一个方法执行时，都将调用处理类的invoke方法
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                myAspect.before();

                //执行目标类的相应方法
                Object result = method.invoke(subjectService, args);

                myAspect.after();

                //返回方法返回值
                return result;
            }
        });
        //返回代理类
        return subjectServiceProxy;
    }
}
